const {ipcMain} = require('electron')
const robot = require('robotjs')
const vkey = require('vkey')

const handleMouse = data => {
    //data {clientX, clientY, screen:{width, height}, video:{width, height} }
    const {clientX, clientY, screen, video} = data
    const x = clientX * screen.width / video.width
    const y = clientY * screen.height / video.height
    robot.moveMouse(x, y)
    robot.mouseClick()
}

const handleKey = data => {
    //data {keyCode, meta, alt, ctrl, shift}
    const modifyKeys = []
    if (data.meta) modifyKeys.push('meta')
    if (data.shift) modifyKeys.push('shift')
    if (data.alt) modifyKeys.push('alt')
    if (data.ctrl) modifyKeys.push('ctrl')
    let key = vkey[data.keyCode].toLowerCase()
    const len = key.length
    if(key[0] === '<' && key[len-1] ==='>'){
        key = key.substr(1, len-2)
    }
    robot.keyTap(key, modifyKeys)
}

module.exports = function () {
    ipcMain.on('robot', (e, type, data) => {
        if (type === 'mouse') {
            handleMouse(data)
        } else if (type === 'key') {
            handleKey(data)
        }
    })
}
